package http.secure.common.util;

import jakarta.servlet.http.HttpServletRequest;
import org.dromara.hutool.extra.spring.SpringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.ServletRequestPathUtils;

import java.lang.reflect.Method;

@Component
public class MappingUtil {

    /**
     * Gets the mapping of the current request URI {@link Method} <br>
     *
     * @param request {@link HttpServletRequest}
     * @return If no matching controller is found or no annotation is specified, null is returned
     */
    public static HandlerMethod getHandlerMethod(HttpServletRequest request) {
        HandlerMapping mapping = SpringUtil.getBean(RequestMappingHandlerMapping.class);
        try {
            ServletRequestPathUtils.parseAndCache(request);
            HandlerExecutionChain chain = mapping.getHandler(request);
            if (chain != null) {
                return (HandlerMethod) chain.getHandler();
            }
        } catch (Exception e) {
            // ignore
        } finally {
            ServletRequestPathUtils.clearParsedRequestPath(request);
        }
        return null;
    }
}
